import { Injectable, Logger } from '@nestjs/common';
import { defaultAxiosConfig } from './common/utils';
import { DocumentService } from './document/document.service';
import { ConfigService } from '@nestjs/config';
import { readFile } from 'fs/promises';
import { lastValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';
import { ApiPath } from './common/api';
import { Response, Request } from 'express';
import { OnlyHttpService } from './shared/only-http/only-http.service';
import { Cron, CronExpression } from '@nestjs/schedule';
import { FileMangerService } from './shared/file-manger/file-manger.service';

@Injectable()
export class AppService {
  dockerServer: string;
  apiServer: string;
  constructor(
    private readonly documentService: DocumentService,
    private readonly config: ConfigService,
    private readonly httpService: HttpService,
    private readonly onlyHttp: OnlyHttpService,
    private readonly fileManger: FileMangerService,
  ) {
    this.dockerServer = this.config.get('ONLYOFFICE_API_URL') as string;
    this.apiServer = this.config.get('API_HOST') as string;
  }

  @Cron(CronExpression.EVERY_5_SECONDS)
  handleCron() {
    this.fileManger.clearTempDirFiles();
  }

  // 处理中转页
  handleHeaderAndFooter = async (req: Request, res: Response) => {
    const urlRuery = req.query;
    const formVerId = urlRuery.form_ver_id || '';
    const token = urlRuery?.access_token;
    const pgroupId = urlRuery?.pgroup_id || 'L001';
    const headers = { Authorization: 'Bearer ' + token };
    const params = { pgroup_id: pgroupId, browse_type: '1' };
    // 获取模版列表
    const headerList = await this.onlyHttp.get<any[]>(ApiPath.Tim.GetHeaderFilePath, { params, headers });
    // console.log('headerList', headerList);
    return res.render('header', { headerList: headerList.data });
  };

  // 直接选择文件
  gotoWithTemplate = async (req: Request, res: Response) => {
    const urlRuery = req.query;
    const formVerId = urlRuery.form_ver_id || '';
    const token = urlRuery?.access_token;
    const pgroupId = urlRuery?.pgroup_id || 'L001';
    const headers = { Authorization: 'Bearer ' + token };
    const params = { pgroup_id: pgroupId, browse_type: '1' };
    // 获取模版列表
    const headerList = await this.onlyHttp.get<any[]>(ApiPath.Tim.GetHeaderFilePath, { params, headers });
    // console.log('headerList', headerList);
    return res.render('header', { headerList: headerList.data });
  };

  // 处理中转页
  handleJumpCenter = async (req: Request, res: Response) => {
    const urlRuery = req.query; //new URLSearchParams(req.);
    // const formVerId = urlParams.get('form_ver_id') || '';
    const token = urlRuery?.access_token;
    const pgroupId = urlRuery?.pgroup_id || '';
    const headers = { Authorization: 'Bearer ' + token };
    const params = { pgroup_id: pgroupId, browse_type: '2' };
    // 获取模版列表
    const headerList = await this.onlyHttp.get<any[]>(ApiPath.Tim.GetHeaderFilePath, { params, headers });
    // console.log('headerList', headerList);
    return res.render('center', { headerList: headerList.data });
  };

  // 获取插件文件配置
  getEditorConfig = async (req: Request) => {
    const config = await this.documentService.getUrlDocAndConfig(req);
    Logger.log(config);
    return {
      apiUrl: this.dockerServer,
      config: config,
    };
  };

  // 根据接口配置
  getTempateConfig = async (req: Request) => {
    const config = await this.documentService.getTemplateAndConfig(req);
    return {
      apiUrl: this.dockerServer,
      config: config,
    };
  };

  // 根据选择文件配置
  getSelectTempateConfig = async (req: Request) => {
    const config = await this.documentService.getSelectTemplateAndConfig(req);
    return {
      apiUrl: this.dockerServer,
      config: config,
    };
  };

  // // 保存文件
  // saveEditor = async () => {
  //   const path = `${this.config.get('domain')}/static/files/test2.docx`;
  //   const fileData = await readFile(path);
  //   const fileDataBase64 = fileData.toString('base64');
  //   return fileDataBase64;
  // };

  // configWorkVerFile = async () => {
  //   const params = { FORM_VER_ID: '' };
  //   const resData = await lastValueFrom(
  //     this.httpService.get(ApiPath.Tim.GetWorkFormVerFile, { params, baseURL: this.apiServer, ...defaultAxiosConfig }),
  //   );
  //   return resData.data;
  // };
}
